//
//  FHStatusListViewModel.swift
//  WeiBo
//
//  Created by qfh on 16/7/13.
//  Copyright © 2016年 qiufuhe. All rights reserved.
//

import UIKit

class FHStatusListViewModel: NSObject {
    
    
   
   
    
    // viewModel 集合
    lazy var statusLists: [FHStatusViewModel] = [FHStatusViewModel]()
    
    //  获取数据
    func loadStatus(isPullUp: Bool, cellBlck: (isSuccess: Bool, message: String)->()) {
        
        var maxid: Int64 = 0
        
        var sinceId: Int64 = 0
        
        var message = "没有加载到最新微博数据"
        
        if isPullUp {
            
            if let count = statusLists.last?.status?.id {
            
                maxid = count - 1
            
            } else {
            
                maxid = 0
            }
            
            
            
        
        } else {
            
            if let cont = statusLists.first?.status?.id {
            
                sinceId = cont + 1
            } else {
            
                sinceId = 0
            }
        
        
        }
    
        
        FHNetTools.shearedNetTools.requestStatus(maxid, since_id: sinceId) { (response, error) -> () in
            
            //            print(response);
            
            guard let dict = response as? [String : AnyObject] else {
                
                print("这不是个json格式")
                
                cellBlck(isSuccess: false, message: message)
                return
            }
            
            guard let dictArray = dict["statuses"] as? [[String : AnyObject]] else {
                
                print("这不是个json格式")
                
                cellBlck(isSuccess: false, message: message)

                return
                
            }
            
            
            var tempArray: [FHStatusViewModel] = [FHStatusViewModel]()
            
            for value in dictArray {
                
                let status = FHStatus(dict: value)
                
                print(status.id)
                
                tempArray.append(FHStatusViewModel(status: status))
                
            }
            
            if isPullUp {
                
                self.statusLists.appendContentsOf(tempArray)

            
            } else {
                
            self.statusLists = tempArray + self.statusLists
            
            }
            
            
            
            
            //  判断服务端的数据是否大于0
            if tempArray.count > 0 {
                message = "加载了\(tempArray.count)条微博数据"
            }
            
            
            cellBlck(isSuccess: true, message: message)
            
            
            
        }
        
    
    }
    
    

}
